package cn.com.cetccst.appstore.ui.fragment.viewmodel;

import android.content.Context;
import android.widget.Toast;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import cn.com.cetccst.appstore.R;
import cn.com.cetccst.appstore.database.AppStoreRepository;
import cn.com.cetccst.appstore.database.model.AppModel;
import cn.com.cetccst.appstore.log.AppStoreLogger;
import cn.com.cetccst.appstore.network.AppStoreHttpRequester;
import cn.com.cetccst.appstore.network.response.AppListResponse;
import cn.com.cetccst.network.BaseCallback;
import cn.com.cetccst.tools.network.Connectivity;
import cn.com.cetccst.tools.ui.ThreadSafeToast;

public class AppListViewModel extends BaseViewModel {

    public static final int TYPE_STORE = 1;
    public static final int TYPE_NEED_UPGRADE = 2;
    private MutableLiveData<DataTrigger> dataTrigger = new MutableLiveData<>(new DataTrigger());

    public final LiveData<List<AppModel>> list = Transformations.switchMap(dataTrigger,
            trigger -> {
                switch (trigger.currentType) {
                    case TYPE_STORE -> {
                        return AppStoreRepository.getInstance().loadAllApps(trigger.currentCategory, trigger.searchKey);
                    }
                    case TYPE_NEED_UPGRADE -> {
                        return AppStoreRepository.getInstance().loadAllNeedUpgradeApps(trigger.searchKey);
                    }
                }

                return AppStoreRepository.getInstance().loadAllApps(trigger.currentCategory, trigger.searchKey);
            });

    protected class DataTrigger {
        public int currentType = TYPE_STORE;
        public String currentCategory;
        public String searchKey;

        public DataTrigger() {
        }

        public DataTrigger(int currentType, String currentCategory, String searchKey) {
            this.currentType = currentType;
            this.currentCategory = currentCategory;
            this.searchKey = searchKey;
        }
    }


    public void setCategory(String currentCategory) {
        Objects.requireNonNull(dataTrigger.getValue()).currentCategory = currentCategory;
        dataTrigger.setValue(dataTrigger.getValue());
    }

    public void setPageType(int currentType) {
        Objects.requireNonNull(dataTrigger.getValue()).currentType = currentType;
        dataTrigger.setValue(dataTrigger.getValue());
//        //初始数据改为需要升级的应用列表
//        if (currentType == TYPE_NEED_UPGRADE)
//            setListData(AppStoreRepository.getInstance().loadAllNeedUpgradeApps());
    }

    public void requestAppList(Context context) {
        if (!isValidSearch(searchKey.getValue())) {
            resetSearchResult();
            ThreadSafeToast.show(context.getString(R.string.store_search_para_error), Toast.LENGTH_SHORT);
            refreshing.setValue(false);
            return;
        }

        Objects.requireNonNull(dataTrigger.getValue()).searchKey = searchKey.getValue();
        dataTrigger.setValue(dataTrigger.getValue());

        //网络请求
        Map<String, String> queryMap = new HashMap<>();
        if (Connectivity.isNetworkConnected(context)) {
            if (AppStoreHttpRequester.getInstance() != null) {
                queryMap.put("limit", "1000");
                //改为创建时间排序，否则更新下载量影响商店列表
                queryMap.put("orderby", "create_time");
                queryMap.put("ascending", "false");
                queryMap.put("with_hidden_apps", "false");
                // 后续本地查，没必要去服务端查找
//                if (!TextUtils.isEmpty(searchKey.getValue())) {
//                    queryMap.put("search", searchKey.getValue());
//                }
                //TODO 这个查询参数不生效，等一体化对接时再重新调
//                if (!TextUtils.isEmpty(currentCategory)) {
//                    queryMap.put("cat", currentCategory);
//                }
            }
        } else {
            ThreadSafeToast.show(R.string.store_error_network_down, Toast.LENGTH_LONG);
            refreshing.setValue(false);
            return;
        }

        refreshing.setValue(true);
        AppStoreHttpRequester.getInstance().requestAllApps(queryMap, new BaseCallback<>() {
            @Override
            public void onResponse(AppListResponse data) {
                refreshing.setValue(false);
                if (data == null) {
                    AppStoreLogger.info("getAllApps response null");
                    ThreadSafeToast.show(R.string.store_network_failed, Toast.LENGTH_SHORT);
                    return;
                }
                if (data.getErrCode() != 0) {
                    ThreadSafeToast.show(context.getString(R.string.store_http_response, data.getErrMessage()), Toast.LENGTH_SHORT);
                } else {
                    for (AppModel appModel : data.getApps()) {
                        appModel.detectAppStatus(context);
                    }
                    AppStoreRepository.getInstance().saveAppModel(data.getApps());
                }
            }
        });
    }

}
